
/* ---- 数据 ---- */
const cats = [
    { id: 'literature', name: '文学' },
    { id: 'tech', name: '科技' },
    { id: 'history', name: '历史' }
];
const books = [
    { id: 1, cat: 'literature', title: '百年孤独', author: '加西亚·马尔克斯', price: 39.50, cover: 'https://img1.doubanio.com/view/subject/l/public/s29053580.jpg' },
    { id: 2, cat: 'literature', title: '活着', author: '余华', price: 28.00, cover: 'https://img1.doubanio.com/view/subject/l/public/s29053580.jpg' },
    { id: 3, cat: 'tech', title: '时间简史', author: '史蒂芬·霍金', price: 45.00, cover: 'https://img1.doubanio.com/view/subject/l/public/s29053580.jpg' },
    { id: 4, cat: 'tech', title: '人工智能', author: '李开复', price: 68.00, cover: 'https://img1.doubanio.com/view/subject/l/public/s29053580.jpg' },
    { id: 5, cat: 'history', title: '史记', author: '司马迁', price: 128.00, cover: 'https://img1.doubanio.com/view/subject/l/public/s29053580.jpg' },
    { id: 6, cat: 'history', title: '万历十五年', author: '黄仁宇', price: 42.00, cover: 'https://img1.doubanio.com/view/subject/l/public/s29053580.jpg' }
];

let current = null;

/* ---- 渲染 ---- */
function renderCat() {
    cat.innerHTML = cats.map(c => `
        <span class="${c.id === current ? 'on' : ''}" onclick="select('${c.id}')">${c.name}</span>
      `).join('');
}
function renderBooks() {
    const list = current ? books.filter(b => b.cat === current) : books;
    booksBox.innerHTML = list.map(b => `
        <div class="card">
          <img src="${b.cover}" alt="">
          <div class="card-body">
            <h6 class="card-title">${b.title}</h6>
            <p class="card-text">作者：${b.author}</p>
            <div class="card-footer-btn">
              <span class="price">￥${b.price.toFixed(1)}</span>
              <button class="btn-sm" onclick="addCart(${b.id},'${b.title}',${b.price},'${b.cover}')">加入购物车</button>
            </div>
          </div>
        </div>
      `).join('');
}
function select(id) {
    current = id;
    renderCat();
    renderBooks();
}

/* ---- 初始化 ---- */
const cat = document.getElementById('cat');
const booksBox = document.getElementById('books');
renderCat();
renderBooks();
